<template>
  <div class="padding-lg">
    <div class="header">发票开出申请单</div>
    <div>
      <el-form v-loading="formLoading" ref="cuForm" :model="cuForm" :rules="rules">
        <table class="mailTable">
          <tr class="firstTr">
            <td class="firstTd" style="width: 20%">
              <span class="required_tip">*</span>所属公司
            </td>
            <td style="width: 40%">
              <el-form-item v-if="!formReadOnly" prop="dept_id">
                <el-select v-model="cuForm.dept_id" style="width: 100%" filterable clearable
                           placeholder="请选择所属公司"
                           @change="deptChange"
                >
                  <el-option v-for="item in company_arr" :key="item.id" :value="item.id" :label="item.head"/>
                </el-select>
              </el-form-item>
              <div v-else>
                {{ cuForm.dept_head }}
              </div>
            </td>
            <td style="width: 20%">
              <span class="required_tip">*</span>组别
            </td>
            <td style="width: 20%">
              <el-form-item v-if="!formReadOnly" prop="group_id">
                <el-select v-model="cuForm.group_id" filterable style="width: 100%" clearable placeholder="请选择组别"
                           @change="groupChange"
                >
                  <el-tooltip v-for="group in group_arr" :key="group.id" effect="dark" placement="right">
                    <div slot="content">
                      <div>组别所含销售单信息</div>
                      <div v-for="(item,index) in group.saleVOList" :key="group.id+''+index">
                        {{
                          item.contract_num + '——' + item.actual_execute_time_start + '~' + item.actual_execute_time_end
                        }}
                      </div>
                    </div>
                    <el-option :label="group.name" :value="group.id"></el-option>
                  </el-tooltip>
                </el-select>
              </el-form-item>
              <div v-else>
                <el-tooltip effect="dark" placement="right">
                  <div slot="content">
                    <div>组别所含销售单信息</div>
                    <div v-for="(item,index) in cuForm.saleVOList" :key="index">
                      {{
                        item.contract_num + '——' + item.actual_execute_time_start + '~' + item.actual_execute_time_end
                      }}
                    </div>
                  </div>
                  <div>{{ cuForm.group_name }}</div>
                </el-tooltip>
              </div>
            </td>
          </tr>
          <tr>
            <td class="firstTd">
              <span class="required_tip">*</span>合同编号
            </td>
            <td colspan="3">
              {{ cuForm.contract_num }}
            </td>
          </tr>
          <tr>
            <td class="firstTd">
              <span class="required_tip">*</span>执行时间
            </td>
            <td colspan="3">
              {{ cuForm.contract_begin_date ? cuForm.contract_begin_date + '~' + cuForm.contract_end_date : '' }}
            </td>
          </tr>
          <tr>
            <td class="firstTd">
              <span class="required_tip">*</span>项目名称
            </td>
            <td colspan="3">
              {{ cuForm.project_name }}
            </td>
          </tr>
          <tr>
            <td class="firstTd">
              <span class="required_tip">*</span>客户归属
            </td>
            <td>
              {{ cuForm.person_in_charge_name }}
            </td>
            <td>
              <span class="required_tip">*</span>维护人
            </td>
            <td>
              {{ cuForm.maintenance_staff_name }}
            </td>
          </tr>
          <tr>
            <td class="firstTd">
              <span class="required_tip">*</span>客户名称
            </td>
            <td colspan="3">
              <el-form-item v-if="!formReadOnly" prop="customer_name">
                <el-input v-model="cuForm.customer_name" placeholder="请输入客户名称" clearable></el-input>
              </el-form-item>
              <div v-else>
                {{ cuForm.customer_name }}
              </div>
            </td>
          </tr>
          <tr>
            <td class="firstTd">
              <span class="required_tip">*</span>地址
            </td>
            <td>
              <el-form-item v-if="!formReadOnly" prop="address">
                <el-input v-model="cuForm.address" type="textarea" autosize placeholder="请输入客户地址" clearable
                ></el-input>
              </el-form-item>
              <div v-else>
                {{ cuForm.address }}
              </div>
            </td>
            <td>
              <span class="required_tip">*</span>电话
            </td>
            <td>
              <el-form-item v-if="!formReadOnly" prop="phone">
                <el-input v-model="cuForm.phone" placeholder="请输入客户电话" clearable></el-input>
              </el-form-item>
              <div v-else>
                {{ cuForm.address }}
              </div>
            </td>
          </tr>
          <tr>
            <td class="firstTd">
              <span class="required_tip">*</span>统一社会信用代码
            </td>
            <td colspan="3">
              <el-form-item v-if="!formReadOnly" prop="company_code">
                <el-input v-model="cuForm.company_code" placeholder="请输入统一社会信用代码" clearable></el-input>
              </el-form-item>
              <div v-else>
                {{ cuForm.company_code }}
              </div>
            </td>
          </tr>
          <tr>
            <td class="firstTd">
              <span class="required_tip">*</span>开户行
            </td>
            <td>
              <el-form-item v-if="!formReadOnly" prop="bank_name">
                <el-input v-model="cuForm.bank_name" placeholder="请输入开户行" clearable></el-input>
              </el-form-item>
              <div v-else>
                {{ cuForm.bank_name }}
              </div>
            </td>
            <td>
              <span class="required_tip">*</span>开户账号
            </td>
            <td>
              <el-form-item v-if="!formReadOnly" prop="bank_account">
                <el-input v-model="cuForm.bank_account" placeholder="请输入开户账号" clearable></el-input>
              </el-form-item>
              <div v-else>
                {{ cuForm.bank_account }}
              </div>
            </td>
          </tr>
          <tr>
            <td class="firstTd">
              <span class="required_tip">*</span>收票单位
            </td>
            <td>
              <el-form-item v-if="!formReadOnly" prop="bill_receipt_company">
                <el-input v-model="cuForm.bill_receipt_company" placeholder="请输入收票单位" clearable></el-input>
              </el-form-item>
              <div v-else>
                {{ cuForm.bill_receipt_company }}
              </div>
            </td>
            <td>
              <span class="required_tip">*</span>发票数量
            </td>
            <td>
              <el-form-item v-if="!formReadOnly" prop="customer_name">
                <el-input type="number" step="1" v-model="cuForm.invoice_quantity" placeholder="请输入发票数量"
                          clearable
                >
                  <template slot="append">份</template>
                </el-input>
              </el-form-item>
              <div v-else>
                {{ cuForm.invoice_quantity + '份' }}
              </div>
            </td>
          </tr>
          <tr>
            <td class="firstTd">
              <span class="required_tip">*</span>业务项目
            </td>
            <td>
              <el-form-item v-if="!formReadOnly" prop="business_project">
                <el-input v-model="cuForm.business_project" placeholder="请输入业务项目" clearable></el-input>
              </el-form-item>
              <div v-else>
                {{ cuForm.business_project }}
              </div>
            </td>
            <td>
              <span class="required_tip">*</span>发票类型
            </td>
            <td>
              <el-form-item v-if="!formReadOnly" prop="invoice_type_id">
                <el-select v-model="cuForm.invoice_type_id" filterable clearable placeholder="请选择发票类型"
                           style="width: 100%"
                >
                  <el-option v-for="item in invoice_type_arr" :key="item.id" :value="item.id" :label="item.name"/>
                </el-select>
              </el-form-item>
              <div v-else>
                {{ cuForm.invoice_type_name }}
              </div>
            </td>
          </tr>
          <tr>
            <td class="firstTd">
              <span class="required_tip" style="color: white;">*</span>发票号码
            </td>
            <td>
              <el-form-item v-if="!formReadOnly" prop="invoice_num">
                <el-input v-model="cuForm.invoice_num" placeholder="请输入发票号码" clearable></el-input>
              </el-form-item>
              <div v-else>
                {{ cuForm.invoice_num }}
              </div>
            </td>
            <td>
              <span class="required_tip">*</span>开票类目
            </td>
            <td>
              <el-form-item v-if="!formReadOnly" prop="invoice_category_id">
                <el-select v-model="cuForm.invoice_category_id" filterable clearable placeholder="请选择开票类目"
                           style="width: 100%"
                >
                  <el-option v-for="item in invoice_category_arr" :key="item.id" :value="item.id" :label="item.name"
                  ></el-option>
                </el-select>
              </el-form-item>
              <div v-else>
                {{ cuForm.invoice_category_name }}
              </div>
            </td>
          </tr>
          <tr>
            <td class="firstTd">
              <span class="required_tip">*</span>发票金额
            </td>
            <td class="text-left">
              <div class="flex flex-no-wrap justify-start">
                <el-form-item v-if="!formReadOnly" prop="invoice_amount">
                  <el-input v-model="cuForm.invoice_amount" type="number" step="0.01" style="width: 200px"
                            placeholder="请输入发票金额"
                            clearable
                  ></el-input>
                </el-form-item>
                <div v-else>
                  {{ cuForm.invoice_amount }}
                </div>
                <span style="text-align: left;margin-left: 5px">
                  {{ invoiceAmountBigString }}
                </span>
              </div>
            </td>
            <td>
              <span class="required_tip">*</span>开票日期
            </td>
            <td>
              <el-form-item v-if="!formReadOnly" prop="invoice_date">
                <el-date-picker
                  v-model="cuForm.invoice_date"
                  type="date"
                  value-format="yyyy-MM-dd"
                  format="yyyy年MM月dd日"
                  placeholder="请选择开票日期"
                  style="width: 100%"
                >
                </el-date-picker>
              </el-form-item>
              <div v-else>
                {{ cuForm.invoice_date }}
              </div>
            </td>
          </tr>
          <tr>
            <td class="firstTd">
              <span class="required_tip">*</span>增项金额
            </td>
            <td class="text-left" colspan="3">
              <div class="flex flex-no-wrap justify-start">
                <el-form-item v-if="!formReadOnly" prop="additional_amount">
                  <el-input v-model="cuForm.additional_amount" type="number" step="0.01" style="width: 200px"
                            placeholder="请输入增项金额"
                            clearable
                  ></el-input>
                </el-form-item>
                <div v-else>
                  {{ cuForm.additional_amount }}
                </div>
                <div style="text-align: left;margin-left: 5px">
                  {{ additionalAmountBigString }}
                </div>
              </div>
            </td>
          </tr>
          <tr>
            <td class="firstTd">
              <span class="required_tip">*</span>开票共计
            </td>
            <td class="text-left" colspan="3">
              <div class="flex flex-no-wrap justify-start">
                <span>{{ cuForm.total_amount }}</span>
                <span style="margin-left: 20px">{{ totalAmountBigString }}</span>
              </div>
            </td>
          </tr>
        </table>
        <div style="text-align: right;padding-right: 20px">申请人：{{ userName }}</div>
      </el-form>
      <div>
        回执：{{ cuForm.applyAttachments && cuForm.applyAttachments.length > 0 ? '' : '暂无' }}
        <el-upload v-if="cuForm.applyAttachments && cuForm.applyAttachments.length>0"
                   :on-preview="handlePreview"
                   :file-list="cuForm.applyAttachments"
                   :disabled="true"
                   action=""
        >
        </el-upload>
      </div>
    </div>
    <div>
      <FlowBtnRow :form-name="'cuForm'" :is-new-data="params.is_created" :can-check="cuForm.can_check"
                  :is-applyer="cuForm.flow_applyer_id == userId" :flow-type="23"
                  :data-id="(params || {}).id || ((params || {}).handle_param || {}).id"
                  :flow-status="cuForm.flow_status"
                  @save="save" @submit="submit" @pass="pass" @returnBack="returnBack" @delete="remove"
                  @actualDelete="actualDelete"
      ></FlowBtnRow>
    </div>
  </div>
</template>

<script>
import FlowBtnRow from '@/components/FlowBtnRow'
import { get_company } from '@/api/system/department'
import { list_all3rd_bycode_contrain_del_close } from '@/api/business/setting/dict'
import { group_list, pass, remove, returnBack, save, saveAndBegin, actualRemove, getDetail } from '@/api/invoice'
import { add, amountToBigStr } from '@/utils/amount'
import { formatDateByFmt } from '@/utils/util'
import { getContractAndCustomerByGroupId } from '@/api/saleOrder/bill_sale_group'

export default {
  name: 'sale_apply_invoice_detail',
  components: { FlowBtnRow },
  data() {
    const validatePhone = (rule, value, callback) => {
      const regExp = /^((0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8})|((0\d{2,3}\-)?([2-9]\d{6,7})+(\-\d{1,6})?)$/
      if (!regExp.test(value)) {
        callback(new Error('请输入正确的电话'))
      } else {
        callback()
      }
    }
    return {
      cuForm: {
        group_id: null, // 分组id
        dept_id: null, // 子公司id
        dept_head: null, // 子公司抬头
        customer_name: null, // 客户名称
        address: null, // 地址
        phone: null, // 电话
        company_code: null, // 统一社会信用代码
        bank_name: null, // 开户行
        bank_account: null, // 开户账户
        bill_receipt_company: null, // 收票单位
        invoice_quantity: null, // 发票数量
        business_project: null, // 业务项目
        invoice_type_id: null, // 发票类型
        invoice_num: null, // 发票号码
        invoice_category_id: null, // 开票类目
        invoice_amount: null, // 发票金额
        invoice_date: null, // 开票日期
        additional_amount: null, // 增项金额
        total_amount: 0, // 开票共计
        person_in_charge_name: null, // 客户负责人名称
        maintenance_staff_name: null, // 客户维护人名称
        group_name: null, // 分组名称
        invoice_type_name: null, // 发票类型名称
        invoice_category_name: null, // 发票类型名称
        flow_applyer_name: null, // 申请人名称
        contract_num: null, // 合同编号
        contract_begin_date: null, // 合同开始时间
        contract_end_date: null, // 合同结束时间
        project_name: null, // 项目名称
        can_check: false, // 是否可以审核
        saleVOList: [] // 组关联的销售单数据
      },
      rules: {
        group_id: [
          { required: true, message: '请选择分组', trigger: 'change' }
        ],
        dept_id: [
          { required: true, message: '请选择所属公司', trigger: 'change' }
        ],
        customer_name: [
          { required: true, message: '请输入客户名称', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入地址', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          {
            validator: validatePhone,
            trigger: 'blur'
          }
        ],
        company_code: [
          { required: true, message: '请输入统一社会信用代码', trigger: 'blur' }
        ],
        bank_name: [
          { required: true, message: '请输入开户行', trigger: 'blur' }
        ],
        bank_account: [
          { required: true, message: '请输入开户账户', trigger: 'blur' }
        ],
        bill_receipt_company: [
          { required: true, message: '请输入收票单位', trigger: 'blur' }
        ],
        invoice_quantity: [
          { required: true, message: '请输入发票数量', trigger: 'blur' }
        ],
        business_project: [
          { required: true, message: '请输入业务项目', trigger: 'blur' }
        ],
        invoice_type_id: [
          { required: true, message: '请选择发票类型', trigger: 'change' }
        ],
        // invoice_num: [
        //   { required: true, message: '请输入发票号码', trigger: 'blur' }
        // ],
        invoice_category_id: [
          { required: true, message: '请选择开票类目', trigger: 'change' }
        ],
        invoice_amount: [
          { required: true, message: '请输入发票金额', trigger: 'blur' }
        ],
        invoice_date: [
          { required: true, message: '请选择开票日期', trigger: 'change' }
        ],
        additional_amount: [
          { required: true, message: '请输入增项金额', trigger: 'blur' }
        ]
      },
      params: {},
      invoice_type_arr: [],
      invoice_category_arr: [],
      company_arr: [],
      group_arr: [],
      formLoading: false
    }
  },
  computed: {
    userId() {
      return this.$store.state.user.id
    },
    userName() {
      return this.cuForm.flow_applyer_name ? this.cuForm.flow_applyer_name : this.$store.state.user.name
    },
    invoiceAmountBigString() {
      return amountToBigStr(this.cuForm.invoice_amount)
    },
    additionalAmountBigString() {
      return amountToBigStr(this.cuForm.additional_amount)
    },
    totalAmountBigString() {
      return amountToBigStr(this.cuForm.total_amount)
    },
    formReadOnly() {
      return this.cuForm.flow_status === 3 || this.cuForm.flow_status === 4
    }
  },
  created() {
    const uuid = this.$route.query.uuid
    this.params = this.$store.state.keep.pageParamsMap.get(uuid)
    if (this.params.is_created) {
      this.cuForm.invoice_date = formatDateByFmt(new Date(), 'yyyy-MM-dd')
    } else {
      if (this.params.id || (this.params.handle_param && this.params.handle_param.id)) {
        const id = this.params.id || (this.params.handle_param && this.params.handle_param.id)
        this.cuForm.id = id
        this.getDetail(id)
      } else {
        this.$message.error('系统异常')
      }
    }
    this.getInvoiceTypeList()
    this.getCompanyList()
    this.getInvoiceCategoryList()
    this.getGroupList()
  },
  methods: {
    getCompanyList() { // 获取公司列表
      get_company().then(res => {
        this.company_arr = res.data
      })
    },
    // 获取开票类目数据
    getInvoiceCategoryList() {
      list_all3rd_bycode_contrain_del_close({
        code: 'fpxg-kplm'
      }).then(res => {
        this.invoice_category_arr = res.data
      })
    },
    // 获取发票类型数据
    getInvoiceTypeList() {
      list_all3rd_bycode_contrain_del_close({
        code: 'fpxg-fplx'
      }).then(res => {
        this.invoice_type_arr = res.data
      })
    },
    // 获取组别待选项列表
    getGroupList() {
      group_list(this.cuForm.id).then(res => {
        this.group_arr = res.data
      })
    },
    deptChange(val) {
      if (val) {
        const find = this.company_arr.find(item => item.id === val)
        if (find) {
          this.cuForm.dept_head = find.head
        } else {
          this.$message.error('系统错误')
          this.cuForm.dept_head = null
        }
      } else {
        this.cuForm.dept_head = null
      }
    },
    // 组别切换的事件
    groupChange(val) {
      if (val) {
        const find = this.group_arr.find(item => item.id === val)
        if (find) {
          this.cuForm.group_name = find.name
        } else {
          this.$message.error('系统错误')
          this.cuForm.group_name = null
        }
        const loading = this.$loading({
          lock: true,
          text: '加载中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        getContractAndCustomerByGroupId(val).then(res => {
          this.cuForm.contract_num = res.data.contract_num
          this.cuForm.contract_begin_date = res.data.contract_begin_date
          this.cuForm.contract_end_date = res.data.contract_end_date
          this.cuForm.project_name = res.data.project_name
          this.cuForm.maintenance_staff_name = res.data.maintenance_staff_name
          this.cuForm.person_in_charge_name = res.data.person_in_charge_name
          this.cuForm.bill_receipt_company = res.data.part_a
          this.cuForm.invoice_amount = res.data.amount
          loading.close()
        }).catch(() => {
          this.cuForm.contract_num = null
          this.cuForm.contract_begin_date = null
          this.cuForm.contract_end_date = null
          this.cuForm.project_name = null
          this.cuForm.maintenance_staff_name = null
          this.cuForm.person_in_charge_name = null
          this.cuForm.bill_receipt_company = null
          this.cuForm.invoice_amount = null
          loading.close()
        })
      } else {
        this.cuForm.group_name = null
      }
    },
    save() {
      const loading = this.$loading({
        lock: true,
        text: '提交中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      save(this.cuForm).then(
        res => {
          if (res.code == 200) {
            this.$message({
              message: res.message,
              type: 'success'
            })
            this.closeThisPage()
          } else {
            this.$message.error('操作失败')
          }
          loading.close()
        }
      ).catch(() => {
        loading.close()
      })
    },
    submit() {
      const loading = this.$loading({
        lock: true,
        text: '提交中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      saveAndBegin(this.cuForm).then(
        res => {
          if (res.code == 200) {
            this.$message({
              message: res.message,
              type: 'success'
            })
            this.closeThisPage()
          } else {
            this.$message.error('操作失败')
          }
          loading.close()
        }
      ).catch(() => {
        loading.close()
      })
    },
    pass(option) {
      const loading = this.$loading({
        lock: true,
        text: '提交中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      pass({
        id: this.cuForm.id,
        wf_check_opinion: option
      }).then(
        res => {
          if (res.code === 200) {
            this.$message({
              message: res.message,
              type: 'success'
            })
            this.closeThisPage()
          } else {
            this.$message.error('操作失败')
          }
          loading.close()
        }
      ).catch(() => {
        loading.close()
      })
    },
    returnBack(option) {
      const loading = this.$loading({
        lock: true,
        text: '提交中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      returnBack({
        id: this.cuForm.id,
        wf_check_opinion: option
      }).then(
        res => {
          if (res.code === 200) {
            this.$message({
              message: res.message,
              type: 'success'
            })
            this.closeThisPage()
          } else {
            this.$message.error('操作失败')
          }
          loading.close()
        }
      ).catch(() => {
        loading.close()
      })
    },
    remove() {
      const loading = this.$loading({
        lock: true,
        text: '提交中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      remove(this.cuForm.id).then(
        res => {
          if (res.code == 200) {
            this.$message({
              message: res.message,
              type: 'success'
            })
            this.closeThisPage()
          } else {
            this.$message.error('操作失败')
          }
          loading.close()
        }
      ).catch(() => {
        loading.close()
      })
    },
    actualDelete() {
      const loading = this.$loading({
        lock: true,
        text: '提交中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      actualRemove(this.cuForm.id).then(
        res => {
          if (res.code == 200) {
            this.$message({
              message: res.message,
              type: 'success'
            })
            this.closeThisPage()
          } else {
            this.$message.error('操作失败')
          }
          loading.close()
        }
      ).catch(() => {
        loading.close()
      })
    },
    closeThisPage() {
      this.$store.dispatch('tagsView/closePage', this.$route.name)
    },
    getDetail(id) {
      this.formLoading = true
      getDetail({ id }).then(res => {
        this.formLoading = false
        this.cuForm = res.data
        this.cuForm.applyAttachments.forEach(item => {
          item.name = item.origin_name
        })
      })
    },
    handlePreview(file) {
      if (file.url) {
        window.open(file.url, '_blank')
      } else {
        this.$message.error('系统异常')
      }
    }
  },
  watch: {
    'cuForm.invoice_amount'(val) {
      let sum = 0
      if (this.cuForm.additional_amount && !isNaN(this.cuForm.additional_amount)) {
        sum = add(this.cuForm.additional_amount, val)
      } else {
        sum = add('0', val)
      }
      this.cuForm.total_amount = sum
    },
    'cuForm.additional_amount'(val) {
      let sum = 0
      if (this.cuForm.invoice_amount && !isNaN(this.cuForm.invoice_amount)) {
        sum = add(this.cuForm.invoice_amount, val)
      } else {
        sum = add('0', val)
      }
      this.cuForm.total_amount = sum
    }
  }
}
</script>

<style scoped>
.mailTable {
  width: 100%;
  font-size: 14px;
  margin: 0 auto 10px auto;
  border-collapse: collapse;
}

.mailTable tr td {
  height: 60px;
  line-height: 35px;
  box-sizing: border-box;
  padding: 0 10px;
  border-bottom: 1px solid #E6EAEE;
  border-right: 1px solid #E6EAEE;
  text-align: center;
}

.firstTr td {
  border-top: 1px solid #E6EAEE;
}

.firstTd {
  border-left: 1px solid #E6EAEE;
}

.header {
  text-align: center;
  font-size: 25px;
  font-weight: bold;
  margin: 10px auto;
}

.required_tip {
  color: red;
}

/deep/ .mailTable .el-form-item {
  margin-bottom: 0;
}

/deep/ .mailTable .el-form-item__content {
  line-height: 0;
}
</style>
